<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Banner;
use App\Models\Family;
use App\Models\FeelingComment;
use App\Models\FeelingLike;
use App\Models\News;
use App\Models\Org;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\User;
use App\Models\UserCollection;
use App\Models\UserInterface;
use App\Models\UserMessage;
use App\Models\UserProject;
use App\Models\UserTeam;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use EasyWeChat\Core\Exception;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;
use EasyWeChat\Foundation\Application;


class IndexController extends Controller
{

    public function info(Request $request)
    {print_r($request);exit;
        //$platformBanner = Banner::orgBanner(0);
        $banner = Banner::orgBanner($this->getOrdId());
        //$banner = array_merge($platformBanner, $orgBanner);

        $blackTeam = Team::where('org_id', $this->getOrdId())->where('in_blacklist', 1)->pluck('id')->toArray();

        $nodes = Project::with('team')->where('org_id', $this->getOrdId())->where('status', 1)->where('verify_status', 1)->whereRaw('recommend_time is not null')->whereNotIn('team_id', $blackTeam);
        $nodes = $nodes->orderBy('publish_time', 'desc');
        $nodes = $nodes->orderBy('id', 'desc');
        $nodes = $nodes->skip(0)->take(10);
        $nodes = $nodes->get();

        foreach($nodes as $node)
        {
            $tmp = Project::format($node);
            $tmp['project_status'] = Project::projectStatus($node);
            $tmp['distance'] = $node->getDistance();
            $tmp['team'] = Team::format($node->team);
            $project[] = $tmp;
        }

        //news

        $nodes = News::where('status', 1)->where('org_id', $this->getOrdId())->orderby('is_recommend', 'desc')->orderBy('publish_time', 'desc')->take(2)->get();
        $news = [];
        foreach($nodes as $value)
        {
            $news[] = News::format($value);
        }


        //$orgInfo = Org::findorfail($this->getOrdId());
        //$orgInfo = Org::format($orgInfo);
        //
        //foreach($orgInfo['module_settings'] as $key=>$value)
        //{
        //    foreach($value as $k=>$v)
        //    {
        //        $orgInfo['module_settings'][$key][$k]['icon'] = image_url($v['icon']);
        //    }
        //}

        $data['banner'] = $banner;
        $data['project'] = $project;
        $data['news'] = $news;
        $data['sanlitun'] = ($this->getOrdId() == 1)? 1:0;
        //$data['org'] = $orgInfo;

        $this->setData($data);
        return $this->response();
    }

    public function userCenter(Request $request)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        //$format = $userInfo->getAllInfo();
        $teamCount = UserTeam::where('user_id', $userInfo->id)->where('verify_status', 1)->count();
        $projectCount = UserProject::where('user_id', $userInfo->id)->where('verify_status', 1)->count();

        $userInterface = UserInterface::where('type', 1)->where('user_id', $userInfo->id)->first();
        $lastTime = empty($userInterface)? $userInfo->created_at:date('Y-m-d H:i:s', $userInterface->last_time);

        $msgCount = UserMessage::where('publish_time', '>', $lastTime)->where(function($query) use ($userInfo){
            $query->where('type', 0)->orwhere(function($q) use ($userInfo){
                $q->where('type', 1)->where('to_user_id', $userInfo->id);
            });
        })->count();

        $userInterface = UserInterface::where('type', 2)->where('user_id', $userInfo->id)->first();
        $lastTime = empty($userInterface)? 0:$userInterface->last_time;
        $newCommentCt = FeelingComment::where('created_at', '>',  date('Y-m-d H:i:s', $lastTime))->where(function($query) use ($userInfo){
            $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})")->orWhereRaw("parent_id in (select id from feeling_tone_comment where user_id={$userInfo->id})");
        })->where('user_id', '!=', $userInfo->id)->count();

        //$newLike = FeelingLike::where('created_at', '>', date('Y-m-d H:i:s', $lastTime))->where(function($query) use ($userInfo) {
        //    $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})");
        //})->count();

        $data['user'] = $userInfo->getAllInfo();
        $data['team_count'] = $teamCount;
        $data['project_count'] = $projectCount;
        $data['msg_count'] = $msgCount;
        $data['comment_count'] = $newCommentCt ;

        $this->setData($data);
        return $this->response();
    }

    public function weixinMedia(Request $request)
    {
        $rules = ['media_id' => 'required'];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }
        $mediaId = $request->input('media_id', '');
        $options = Org::getWechatConf();
        if($options == false)
        {
            Log::error('获取机构信息出错 host:'.request()->header('X-org-code', ''));
            return '服务器忙,请稍后再试';
        }
        try{
            $storage = Storage::disk(config('filesystems.default'));
            $path = '/'.date('Y-m-d').'/';
            $storage->makeDirectory($path);
            $dir =  config('filesystems.disks.'.config('filesystems.default').'.root').$path;

            $app = new Application($options);
            // 临时素材
            $temporary = $app->material_temporary;
            $filename = $temporary->download($mediaId, $dir);
            $url = config('filesystems.base_url').$path.$filename;

            $this->setData(['url'=>$url]);
        }catch (\Exception $e) {
            $this->setStatus($e->getCode());
            $this->setMsg($e->getMessage());
        }

        return $this->response();
    }

}
